const wasmBrowserInstantiate = async (wasmModuleUrl, importObject) => {
    let response = undefined;

    if (!importObject) {
        importObject = {
            env: {
                abort: () => console.log("Abort!"),
            },
        };
    }

    // 检查浏览器是否支持流实例化
    if (WebAssembly.instantiateStreaming) {
        // 获取模块，并在下载时实例化它
        response = await WebAssembly.instantiateStreaming(
            fetch(wasmModuleUrl),
            importObject
        );
    } else {
        const fetchAndInstantiateTask = async () => {
            const wasmArrayBuffer = await fetch(wasmModuleUrl).then(
                (response) => response.arrayBuffer()
            );
            return WebAssembly.instantiate(wasmArrayBuffer, importObject);
        };
        response = await fetchAndInstantiateTask();
    }

    return response;
};

const runWasm = async () => {
    // 实例化wasm模块
    const wasmModule = await wasmBrowserInstantiate("./build/release.wasm");

    // 从wasm 调用 add 函数
    const addResult = wasmModule.instance.exports.add(25, 24);

    // 将函数执行结果加入到 DOM中
    document.getElementById(
        "result"
    ).innerHTML = `Hello World! addResult: ${addResult}`;
};
runWasm();